import * as React from 'react';
import {
  TimePicker,
  Form,
  Input,
  Modal,
  Select,
  message,
  DatePicker,
  Divider,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import request from '@/http';
import './cEdit.less';
const { Option } = Select;

import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import qs from 'qs';
import { useState } from 'react';
import { any } from 'prop-types';

const { confirm } = Modal;

interface CourseEditObject {
  isModalVisible: boolean;
  id?: number;
  projectDate?: any;
  courseName?: number;
  trainTeacher?: string;
  dutyTeacher?: string;
  signInTime?: string;
  signOutTime?: string;
  classRome?: string;
  remark?: string;
}

const CEdit = (props: { editObject: CourseEditObject }) => {
  const { editObject } = props;
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [formObject] = Form.useForm();

  const modelOnOk = async () => {
    const data = await formObject.validateFields();
    console.log(data);
    const ds = {
      classRome: data.classRome,
      courseName: data.courseName,
      courseOnId: editObject.id,
      dutyTeacherId: data.dutyTeacherId,
      projectDate: moment(data.projectDate).format('YYYY-MM-DD'),
      signInTime: moment(data.signInTime).format('hh:mm:ss'),
      signOutTime: moment(data.signOutTime).format('hh:mm:ss'),
      trainTeachers: data.trainTeachers.toString(),
      remark: data.remark,
    };
    console.log(ds);
    const result: any = await request.post(
      '/api/admin/course/InsertCourse',
      qs.stringify(ds),
      { headers: { 'content-type': 'application/x-www-form-urlencoded' } },
    );
    if (result.success) {
      setIsModalVisible(false);
      message.success('用户添加成功');
      location.reload();
    } else {
      message.error(result.message);
      setIsModalVisible(true);
    }
  };

  const modelOnCancel = () => {
    setIsModalVisible(false);
  };

  React.useEffect(() => {
    setIsModalVisible(editObject.isModalVisible);
    if (editObject.id != null) {
      console.log(editObject);
      console.log(formObject.getFieldsValue());
      formObject.setFieldsValue({
        id: editObject.id,
        projectDate: editObject.projectDate
          ? moment(editObject.projectDate)
          : null,
        courseName: editObject.courseName,
        trainTeachers: editObject.trainTeacher,
        dutyTeacherId: editObject.dutyTeacher,
        signInTime: editObject.signInTime,
        signOutTime: editObject.signOutTime,
        classRome: editObject.classRome,
        remark: editObject.remark,
      });
    }
  }, [editObject]);

  const layout = {
    labelCol: { span: 12 },
    wrapperCol: { span: 12 },
  };

  /**
   * 项目下拉菜单
   */
  const flag = editObject.id !== null && editObject.id !== undefined;
  const [mSelect, setMSelect] = useState({
    name: '',
  });
  const [items, setItems] = useState([]);
  //连接后端服务器，数据获取
  const loadSelect = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getCourse',
    );
    if (result.success) {
      setItems(result.data);
      console.log(result.data);
    }
  };

  const onNameChange = (event: any) => {
    setMSelect(event.target.value);
  };

  //新增项目名称
  const addItem = (e: any) => {
    console.log(mSelect);
    let item: any = [];
    item.push({ courseName: mSelect });
    for (let i = 0; i < items.length; i++) {
      item.push(items[i]);
    }
    setItems(item);
    console.log(items);
    console.log(item);
  };

  //教师下拉菜单
  const [select, setSelect] = useState([]);
  const loadSelect2 = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getTeacher',
    );
    if (result.success) {
      setSelect(result.data);
    }
  };

  React.useEffect(() => {
    loadSelect2().then();
    loadSelect().finally();
  }, []);

  return (
    <>
      <Modal
        width={1200}
        className="modal"
        title={flag ? ' 编辑' : '新增'}
        visible={isModalVisible}
        onCancel={modelOnCancel}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText="确认"
        cancelText="取消"
      >
        <Form
          className="form"
          name="editForm"
          form={formObject}
          preserve={false}
        >
          <Form.Item
            label="日&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;期"
            name="projectDate"
            style={{ marginBottom: 20 }}
          >
            <DatePicker style={{ height: '30px', width: 160 }} />
            {/*<Input placeholder="请输入"/>*/}
          </Form.Item>

          <Form.Item
            label="项目名称"
            name="courseName"
            style={{ marginBottom: 20 }}
          >
            <Select
              style={{ width: 160 }}
              placeholder="请选择"
              dropdownRender={(menu) => (
                <div>
                  {menu}
                  <Divider style={{ margin: '4px, 0' }} />
                  <div
                    style={{ display: 'flex', flexWrap: 'nowrap', padding: 4 }}
                  >
                    <Input
                      style={{ width: '120px' }}
                      value={mSelect.name}
                      onChange={onNameChange}
                    />
                    <a
                      style={{
                        flex: 'none',
                        padding: '4px',
                        display: 'block',
                        cursor: 'pointer',
                      }}
                      onClick={addItem}
                    >
                      <PlusOutlined /> 新增项目
                    </a>
                  </div>
                </div>
              )}
            >
              {items.map((item: any) => (
                <Option key={item} value={item.courseName}>
                  {item.courseName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="实训老师"
            name="trainTeachers"
            style={{ marginBottom: 20 }}
          >
            <Select
              mode="tags"
              placeholder="请选择..."
              optionFilterProp="children"
              style={{ width: 180, height: '35px', overflowY: 'scroll' }}
              filterOption={(input, option: any) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              filterSort={(optionA, optionB) =>
                optionA.children
                  .toLowerCase()
                  .localeCompare(optionB.children.toLowerCase())
              }
            >
              {select.map((item: any) => {
                return (
                  <Option value={item.teacherId}>{item.teacherName}</Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item label="责任老师" name="dutyTeacherId">
            <Select
              placeholder="请选择..."
              optionFilterProp="children"
              style={{ width: 160 }}
              filterOption={(input, option: any) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              filterSort={(optionA, optionB) =>
                optionA.children
                  .toLowerCase()
                  .localeCompare(optionB.children.toLowerCase())
              }
            >
              {select.map((item: any) => {
                return (
                  <Option value={item.teacherId}>{item.teacherName}</Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item label="签到时间" name="signInTime">
            <TimePicker style={{ width: 160 }} />
          </Form.Item>
          <Form.Item label="签退时间" name="signOutTime">
            <TimePicker style={{ width: 160 }} />
          </Form.Item>
          <Form.Item
            label="教&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;室"
            name="classRome"
          >
            <Input style={{ width: 160 }} placeholder="请输入" />
          </Form.Item>
          <Form.Item
            style={{ width: 400 }}
            label="备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注"
            name="remark"
          >
            <Input style={{ width: 260 }} placeholder="请输入" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export { CEdit, CourseEditObject };
